/*
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.lang.reflect;

import java.lang.annotation.Annotation;
import java.lang.annotation.AnnotationFormatError;
import java.lang.annotation.Repeatable;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import sun.reflect.annotation.AnnotationSupport;
import sun.reflect.annotation.AnnotationType;

/**
 * 表示当前在此 VM 中运行的程序的注解元素。
 * 此接口允许通过反射读取注解。此接口中的方法返回的所有注解都是不可变的和可序列化的。
 * 此接口的方法返回的数组可以由调用者修改，而不会影响返回给其他调用者的数组。
 *
 * <p>{@link #getAnnotationsByType(Class)} 和 {@link
 * #getDeclaredAnnotationsByType(Class)} 方法支持元素上相同类型的多个注解。
 * 如果任一方法的参数是可重复注解类型（JLS 9.6），则该方法将"透视"容器注解（JLS 9.7）
 * （如果存在），并返回容器内的任何注解。容器注解可能在编译时生成，
 * 以包装参数类型的多个注解。
 *
 * <p>术语<em>直接存在</em>、<em>间接存在</em>、<em>存在</em>和<em>关联</em>
 * 在整个接口中用于精确描述方法返回哪些注解：
 *
 * <ul>
 *
 * <li> 如果元素 <i>E</i> 具有 {@code RuntimeVisibleAnnotations} 或
 * {@code RuntimeVisibleParameterAnnotations} 或 {@code RuntimeVisibleTypeAnnotations}
 * 属性，且该属性包含注解 <i>A</i>，则注解 <i>A</i> <em>直接存在</em>于元素 <i>E</i> 上。
 *
 * <li>如果元素 <i>E</i> 具有 {@code RuntimeVisibleAnnotations} 或
 * {@code RuntimeVisibleParameterAnnotations} 或 {@code RuntimeVisibleTypeAnnotations}
 * 属性，且 <i>A</i> 的类型是可重复的，且该属性恰好包含一个注解，
 * 其值元素包含 <i>A</i> 且其类型是 <i>A</i> 类型的容器注解类型，
 * 则注解 <i>A</i> <em>间接存在</em>于元素 <i>E</i> 上。
 *
 * <li>如果满足以下任一条件，则注解 <i>A</i> 存在于元素 <i>E</i> 上：
 *
 * <ul>
 *
 * <li><i>A</i> 直接存在于 <i>E</i> 上；或
 *
 * <li><i>A</i> 类型的注解不直接存在于 <i>E</i> 上，且 <i>E</i> 是一个类，
 * 且 <i>A</i> 的类型是可继承的，且 <i>A</i> 存在于 <i>E</i> 的超类上。
 *
 * </ul>
 *
 * <li>如果满足以下任一条件，则注解 <i>A</i> 与元素 <i>E</i> <em>关联</em>：
 *
 * <ul>
 *
 * <li><i>A</i> 直接或间接存在于 <i>E</i> 上；或
 *
 * <li><i>A</i> 类型的注解不直接或间接存在于 <i>E</i> 上，且 <i>E</i> 是一个类，
 * 且 <i>A</i> 的类型是可继承的，且 <i>A</i> 与 <i>E</i> 的超类关联。
 *
 * </ul>
 *
 * </ul>
 *
 * <p>下表总结了此接口中不同方法检查哪种注解存在性。
 *
 * <table border>
 * <caption>不同 AnnotatedElement 方法检测到的存在性类型概述</caption>
 * <tr><th colspan=2></th><th colspan=4>存在性类型</th>
 * <tr><th colspan=2>方法</th><th>直接存在</th><th>间接存在</th><th>存在</th><th>关联</th>
 * <tr><td align=right>{@code T}</td><td>{@link #getAnnotation(Class) getAnnotation(Class&lt;T&gt;)}
 * <td></td><td></td><td>X</td><td></td>
 * </tr>
 * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getAnnotations getAnnotations()}
 * <td></td><td></td><td>X</td><td></td>
 * </tr>
 * <tr><td align=right>{@code T[]}</td><td>{@link #getAnnotationsByType(Class) getAnnotationsByType(Class&lt;T&gt;)}
 * <td></td><td></td><td></td><td>X</td>
 * </tr>
 * <tr><td align=right>{@code T}</td><td>{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class&lt;T&gt;)}
 * <td>X</td><td></td><td></td><td></td>
 * </tr>
 * <tr><td align=right>{@code Annotation[]}</td><td>{@link #getDeclaredAnnotations getDeclaredAnnotations()}
 * <td>X</td><td></td><td></td><td></td>
 * </tr>
 * <tr><td align=right>{@code T[]}</td><td>{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class&lt;T&gt;)}
 * <td>X</td><td>X</td><td></td><td></td>
 * </tr>
 * </table>
 *
 * <p>对于 {@code get[Declared]AnnotationsByType( Class <
 * T >)} 的调用，直接或间接存在于元素 <i>E</i> 上的注解的顺序
 * 按如下方式计算：间接存在于 <i>E</i> 上的注解被视为直接存在于 <i>E</i> 上，
 * 代替其容器注解，按它们在容器注解的值元素中出现的顺序排列。
 *
 * <p>如果注解类型 <i>T</i> 最初<em>不是</em>可重复的，
 * 后来修改为可重复的，需要记住几个兼容性问题。
 *
 * <i>T</i> 的容器注解类型是 <i>TC</i>。
 *
 * <ul>
 *
 * <li>Modifying <i>T</i> to be repeatable is source and binary
 * compatible with existing uses of <i>T</i> and with existing uses
 * of <i>TC</i>.
 *
 * That is, for source compatibility, source code with annotations of
 * type <i>T</i> or of type <i>TC</i> will still compile. For binary
 * compatibility, class files with annotations of type <i>T</i> or of
 * type <i>TC</i> (or with other kinds of uses of type <i>T</i> or of
 * type <i>TC</i>) will link against the modified version of <i>T</i>
 * if they linked against the earlier version.
 *
 * (An annotation type <i>TC</i> may informally serve as an acting
 * containing annotation type before <i>T</i> is modified to be
 * formally repeatable. Alternatively, when <i>T</i> is made
 * repeatable, <i>TC</i> can be introduced as a new type.)
 *
 * <li>If an annotation type <i>TC</i> is present on an element, and
 * <i>T</i> is modified to be repeatable with <i>TC</i> as its
 * containing annotation type then:
 *
 * <ul>
 *
 * <li>The change to <i>T</i> is behaviorally compatible with respect
 * to the {@code get[Declared]Annotation(Class<T>)} (called with an
 * argument of <i>T</i> or <i>TC</i>) and {@code
 * get[Declared]Annotations()} methods because the results of the
 * methods will not change due to <i>TC</i> becoming the containing
 * annotation type for <i>T</i>.
 *
 * <li>The change to <i>T</i> changes the results of the {@code
 * get[Declared]AnnotationsByType(Class<T>)} methods called with an
 * argument of <i>T</i>, because those methods will now recognize an
 * annotation of type <i>TC</i> as a container annotation for <i>T</i>
 * and will "look through" it to expose annotations of type <i>T</i>.
 *
 * </ul>
 *
 * <li>If an annotation of type <i>T</i> is present on an
 * element and <i>T</i> is made repeatable and more annotations of
 * type <i>T</i> are added to the element:
 *
 * <ul>
 *
 * <li> The addition of the annotations of type <i>T</i> is both
 * source compatible and binary compatible.
 *
 * <li>The addition of the annotations of type <i>T</i> changes the results
 * of the {@code get[Declared]Annotation(Class<T>)} methods and {@code
 * get[Declared]Annotations()} methods, because those methods will now
 * only see a container annotation on the element and not see an
 * annotation of type <i>T</i>.
 *
 * <li>The addition of the annotations of type <i>T</i> changes the
 * results of the {@code get[Declared]AnnotationsByType(Class<T>)}
 * methods, because their results will expose the additional
 * annotations of type <i>T</i> whereas previously they exposed only a
 * single annotation of type <i>T</i>.
 *
 * </ul>
 *
 * </ul>
 *
 * <p>如果此接口中的方法返回的注解包含（直接或间接）引用在此 VM 中不可访问的类的
 * {@link Class} 值成员，尝试通过在返回的注解上调用相关的返回 Class 的方法来读取该类
 * 将导致 {@link TypeNotPresentException}。
 *
 * <p>类似地，如果注解中的枚举常量在枚举类型中不再存在，
 * 尝试读取枚举值成员将导致 {@link EnumConstantNotPresentException}。
 *
 * <p>如果注解类型 <i>T</i> 被（元）注解为 {@code @Repeatable} 注解，
 * 其值元素指示类型 <i>TC</i>，但 <i>TC</i> 未声明返回类型为 <i>T</i>{@code []} 的
 * {@code value()} 方法，则抛出 {@link java.lang.annotation.AnnotationFormatError} 类型的异常。
 *
 * <p>最后，尝试读取定义已不兼容演化的成员将导致
 * {@link java.lang.annotation.AnnotationTypeMismatchException} 或
 * {@link java.lang.annotation.IncompleteAnnotationException}。
 *
 * @see java.lang.EnumConstantNotPresentException
 * @see java.lang.TypeNotPresentException
 * @see AnnotationFormatError
 * @see java.lang.annotation.AnnotationTypeMismatchException
 * @see java.lang.annotation.IncompleteAnnotationException
 * @since 1.5
 * @author Josh Bloch
 */
public interface AnnotatedElement {
    /**
     * 如果指定类型的注解<em>存在</em>于此元素上，则返回 true，否则返回 false。
     * 此方法主要设计用于方便地访问标记注解。
     *
     * <p>此方法返回的真值等价于：
     * {@code getAnnotation(annotationClass) != null}
     *
     * <p>默认方法的主体被指定为上述代码。
     *
     * @param annotationClass 对应于注解类型的 Class 对象
     * @return 如果指定注解类型的注解存在于此元素上，则返回 true，否则返回 false
     * @throws NullPointerException 如果给定的注解类为 null
     * @since 1.5
     */
    default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
        return getAnnotation(annotationClass) != null;
    }

   /**
     * 如果指定类型的注解<em>存在</em>，则返回此元素的该注解，否则返回 null。
     *
     * @param <T> 要查询并返回的注解类型（如果存在）
     * @param annotationClass 对应于注解类型的 Class 对象
     * @return 如果此元素上存在指定注解类型的注解，则返回该注解，否则返回 null
     * @throws NullPointerException 如果给定的注解类为 null
     * @since 1.5
     */
    <T extends Annotation> T getAnnotation(Class<T> annotationClass);

    /**
     * 返回<em>存在</em>于此元素上的注解。
     *
     * 如果此元素上没有<em>存在</em>的注解，则返回值是长度为 0 的数组。
     *
     * 此方法的调用者可以自由修改返回的数组；这不会影响返回给其他调用者的数组。
     *
     * @return 存在于此元素上的注解
     * @since 1.5
     */
    Annotation[] getAnnotations();

    /**
     * Returns annotations that are <em>associated</em> with this element.
     *
     * If there are no annotations <em>associated</em> with this element, the return
     * value is an array of length 0.
     *
     * The difference between this method and {@link #getAnnotation(Class)}
     * is that this method detects if its argument is a <em>repeatable
     * annotation type</em> (JLS 9.6), and if so, attempts to find one or
     * more annotations of that type by "looking through" a container
     * annotation.
     *
     * The caller of this method is free to modify the returned array; it will
     * have no effect on the arrays returned to other callers.
     *
     * @implSpec The default implementation first calls {@link
     * #getDeclaredAnnotationsByType(Class)} passing {@code
     * annotationClass} as the argument. If the returned array has
     * length greater than zero, the array is returned. If the returned
     * array is zero-length and this {@code AnnotatedElement} is a
     * class and the argument type is an inheritable annotation type,
     * and the superclass of this {@code AnnotatedElement} is non-null,
     * then the returned result is the result of calling {@link
     * #getAnnotationsByType(Class)} on the superclass with {@code
     * annotationClass} as the argument. Otherwise, a zero-length
     * array is returned.
     *
     * @param <T> the type of the annotation to query for and return if present
     * @param annotationClass the Class object corresponding to the
     *        annotation type
     * @return all this element's annotations for the specified annotation type if
     *     associated with this element, else an array of length zero
     * @throws NullPointerException if the given annotation class is null
     * @since 1.8
     */
    default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
         /*
          * Definition of associated: directly or indirectly present OR
          * neither directly nor indirectly present AND the element is
          * a Class, the annotation type is inheritable, and the
          * annotation type is associated with the superclass of the
          * element.
          */
         T[] result = getDeclaredAnnotationsByType(annotationClass);

         if (result.length == 0 && // Neither directly nor indirectly present
             this instanceof Class && // the element is a class
             AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
             Class<?> superClass = ((Class<?>) this).getSuperclass();
             if (superClass != null) {
                 // Determine if the annotation is associated with the
                 // superclass
                 result = superClass.getAnnotationsByType(annotationClass);
             }
         }

         return result;
     }

    /**
     * Returns this element's annotation for the specified type if
     * such an annotation is <em>directly present</em>, else null.
     *
     * This method ignores inherited annotations. (Returns null if no
     * annotations are directly present on this element.)
     *
     * @implSpec The default implementation first performs a null check
     * and then loops over the results of {@link
     * #getDeclaredAnnotations} returning the first annotation whose
     * annotation type matches the argument type.
     *
     * @param <T> the type of the annotation to query for and return if directly present
     * @param annotationClass the Class object corresponding to the
     *        annotation type
     * @return this element's annotation for the specified annotation type if
     *     directly present on this element, else null
     * @throws NullPointerException if the given annotation class is null
     * @since 1.8
     */
    default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
         Objects.requireNonNull(annotationClass);
         // Loop over all directly-present annotations looking for a matching one
         for (Annotation annotation : getDeclaredAnnotations()) {
             if (annotationClass.equals(annotation.annotationType())) {
                 // More robust to do a dynamic cast at runtime instead
                 // of compile-time only.
                 return annotationClass.cast(annotation);
             }
         }
         return null;
     }

    /**
     * Returns this element's annotation(s) for the specified type if
     * such annotations are either <em>directly present</em> or
     * <em>indirectly present</em>. This method ignores inherited
     * annotations.
     *
     * If there are no specified annotations directly or indirectly
     * present on this element, the return value is an array of length
     * 0.
     *
     * The difference between this method and {@link
     * #getDeclaredAnnotation(Class)} is that this method detects if its
     * argument is a <em>repeatable annotation type</em> (JLS 9.6), and if so,
     * attempts to find one or more annotations of that type by "looking
     * through" a container annotation if one is present.
     *
     * The caller of this method is free to modify the returned array; it will
     * have no effect on the arrays returned to other callers.
     *
     * @implSpec The default implementation may call {@link
     * #getDeclaredAnnotation(Class)} one or more times to find a
     * directly present annotation and, if the annotation type is
     * repeatable, to find a container annotation. If annotations of
     * the annotation type {@code annotationClass} are found to be both
     * directly and indirectly present, then {@link
     * #getDeclaredAnnotations()} will get called to determine the
     * order of the elements in the returned array.
     *
     * <p>Alternatively, the default implementation may call {@link
     * #getDeclaredAnnotations()} a single time and the returned array
     * examined for both directly and indirectly present
     * annotations. The results of calling {@link
     * #getDeclaredAnnotations()} are assumed to be consistent with the
     * results of calling {@link #getDeclaredAnnotation(Class)}.
     *
     * @param <T> the type of the annotation to query for and return
     * if directly or indirectly present
     * @param annotationClass the Class object corresponding to the
     *        annotation type
     * @return all this element's annotations for the specified annotation type if
     *     directly or indirectly present on this element, else an array of length zero
     * @throws NullPointerException if the given annotation class is null
     * @since 1.8
     */
    default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
        Objects.requireNonNull(annotationClass);
        return AnnotationSupport.
            getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
                                            collect(Collectors.toMap(Annotation::annotationType,
                                                                     Function.identity(),
                                                                     ((first,second) -> first),
                                                                     LinkedHashMap::new)),
                                            annotationClass);
    }

    /**
     * Returns annotations that are <em>directly present</em> on this element.
     * This method ignores inherited annotations.
     *
     * If there are no annotations <em>directly present</em> on this element,
     * the return value is an array of length 0.
     *
     * The caller of this method is free to modify the returned array; it will
     * have no effect on the arrays returned to other callers.
     *
     * @return annotations directly present on this element
     * @since 1.5
     */
    Annotation[] getDeclaredAnnotations();
}
